package net.viralpatel.struts2;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.*;

import org.apache.commons.codec.digest.DigestUtils;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class LoginUserAction extends ActionSupport {
	
	private static final long serialVersionUID = 1L;
	private String username;
	private String password;

	public String execute() throws Exception {

		String url = "jdbc:mysql://localhost:3306/";
		String dbName = "t10";
		String driverName = "com.mysql.jdbc.Driver";
		Connection con = null;
		ResultSet resultSet = null;
		String nameroot = "root";
		String passwordroot = "";
		try {
			Class.forName(driverName);
			con = DriverManager.getConnection(url + dbName,nameroot,passwordroot);
		} catch (ClassNotFoundException e) {
			System.out.println(e.getMessage());	
		}catch(Exception e){
			System.out.println(e.getMessage());
		}
		String passMd5= DigestUtils.md5Hex( this.password);
		String selectLogin = "SELECT * FROM user WHERE userID = ? and password = ? and priority = 0 and state=1";
		PreparedStatement prepStmt = con.prepareStatement(selectLogin);
		prepStmt.setString(1, this.username);
		//System.out.println(DigestUtils.md5Hex( this.password));
		prepStmt.setString(2, passMd5);
		resultSet = prepStmt.executeQuery();
		resultSet.last();
		int rowCol = resultSet.getRow();
		if (rowCol == 1) {
			Map session = ActionContext.getContext().getSession();
			session.put("username", this.username);
			session.put("password",passMd5);
			session.put("loggedinuser", "true");
			con.close();
			return SUCCESS;
		} else {
			addActionError(getText("error.login"));
			con.close();
			return ERROR;
		}
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}